package com.mynews.activities.admin;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Intent;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.lifecycle.AndroidViewModel;

import com.mynews.activities.App;
import com.mynews.activities.detail.DetailActivity;
import com.mynews.adapter.TipOffAdp;
import com.mynews.bean.NewsBean;
import com.mynews.bean.TipOffBean;
import com.mynews.bean.User;
import com.mynews.databinding.ActivityAdminBinding;
import com.mynews.utils.BmobApi;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AdminVM extends AndroidViewModel {
    @SuppressLint("StaticFieldLeak")
    private static AdminActivity adminActivity;
    @SuppressLint("StaticFieldLeak")
    private static ActivityAdminBinding binding;
    private final List<TipOffBean> data=new ArrayList<>();
    public AdminVM(@NonNull Application application) {
        super(application);
    }
    public void setBinding(ActivityAdminBinding binding, AdminActivity adminActivity) {
        AdminVM.binding=binding;
        AdminVM.adminActivity=adminActivity;
        binding.setAdp(new TipOffAdp(adminActivity,data));
        binding.adminList.setOnItemClickListener((parent, view, position, id) -> {
            //点击进去查看新闻，
            TipOffBean bean = data.get(position);
            if (bean.newsId.equals("")){
                Toast.makeText(adminActivity, "该新闻已被删除", Toast.LENGTH_SHORT).show();
            }else {
                App.newsBean=bean.newsBean;
                adminActivity.startActivity(new Intent(adminActivity, DetailActivity.class));
            }
        });
        binding.adminList.setOnItemLongClickListener((parent, view, position, id) -> {
            TipOffBean bean = data.get(position);
//            if (bean.newsId.equals("")){//过滤Bean只留下未受理不会有此结果
//                Toast.makeText(adminActivity, "该新闻已被删除", Toast.LENGTH_SHORT).show();
//            }else if(bean.process.equals("已驳回")){//过滤Bean只留下未受理不会有此结果
//                Toast.makeText(adminActivity, "该举报已被驳回", Toast.LENGTH_SHORT).show();
//            }else {
//                AlertDialog.Builder dialog=new AlertDialog.Builder(adminActivity);
//                dialog.setTitle("提示").setItems(new String[]{"删除该新闻并提示用户举报成功","驳回该举报"}, (dialog1, which) -> {
//                    try {
//                        JSONObject jo=new JSONObject();
//                        switch (which){
//                            case 0:
//                                jo.put("process","已受理并删除该新闻");
//                                BmobApi.put(jo, "https://api2.bmob.cn/1/classes/tipoff/"+bean.id, false, new Callback() {
//                                    @Override
//                                    public void onFailure(@NotNull Call call, @NotNull IOException e) { }
//                                    @Override
//                                    public void onResponse(@NotNull Call call, @NotNull Response response) {
//                                        refresh();
//                                    }
//                                });
//                                BmobApi.delete("https://api2.bmob.cn/1/classes/news/"+bean.newsId, new Callback() {
//                                    @Override
//                                    public void onFailure(@NotNull Call call, @NotNull IOException e) { }
//                                    @Override
//                                    public void onResponse(@NotNull Call call, @NotNull Response response) {
//                                    }
//                                });
//                                deleteTable("reply", data.get(position).id);
//                                deleteTable("comment", data.get(position).id);
//                                deleteTable("like", data.get(position).id);
//                                deleteTable("collection", data.get(position).id);
//                                break;
//                            case 1:
//                                jo.put("process","已驳回");
//                                BmobApi.put(jo, "https://api2.bmob.cn/1/classes/tipoff/"+bean.id, false, new Callback() {
//                                    @Override
//                                    public void onFailure(@NotNull Call call, @NotNull IOException e) { }
//                                    @Override
//                                    public void onResponse(@NotNull Call call, @NotNull Response response) { refresh(); }
//                                });
//                                break;
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }).show();
//            }
            if (bean.process.equals("待受理")){
                AlertDialog.Builder dialog=new AlertDialog.Builder(adminActivity);
                dialog.setTitle("提示").setItems(new String[]{"删除该新闻并提示用户举报成功","驳回该举报"}, (dialog1, which) -> {
                    try {
                        JSONObject jo=new JSONObject();
                        switch (which){
                            case 0:
                                jo.put("process","已受理并删除该新闻");
                                BmobApi.put(jo, "https://api2.bmob.cn/1/classes/tipoff/"+bean.id, false, new Callback() {
                                    @Override
                                    public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                                    @Override
                                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                                        refresh();
                                    }
                                });
                                BmobApi.delete("https://api2.bmob.cn/1/classes/news/"+bean.newsId, new Callback() {
                                    @Override
                                    public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                                    @Override
                                    public void onResponse(@NotNull Call call, @NotNull Response response) {
                                    }
                                });
                                deleteTable("reply", data.get(position).id);
                                deleteTable("comment", data.get(position).id);
                                deleteTable("like", data.get(position).id);
                                deleteTable("collection", data.get(position).id);
                                break;
                            case 1:
                                jo.put("process","已驳回");
                                BmobApi.put(jo, "https://api2.bmob.cn/1/classes/tipoff/"+bean.id, false, new Callback() {
                                    @Override
                                    public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                                    @Override
                                    public void onResponse(@NotNull Call call, @NotNull Response response) { refresh(); }
                                });
                                break;
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }).show();
            }
            return true;
        });
        refresh();
    }
    private void deleteTable(String tableName, String value) {
        BmobApi.get("https://api2.bmob.cn/1/classes/"+tableName+"?where="+ URLEncoder.encode("{\""+ "newsId" +"\":\""+value+"\"}"), new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {
                    assert response.body() != null;
                    JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                    for (int i = 0; i < ja.length(); i++) {
                        BmobApi.delete("https://api2.bmob.cn/1/classes/"+tableName+"/"+ja.getJSONObject(i).getString("objectId"), new Callback() {
                            @Override
                            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                            @Override
                            public void onResponse(@NotNull Call call, @NotNull Response response) { }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }
    private void refresh() {
        data.clear();
        BmobApi.get("https://api2.bmob.cn/1/classes/tipoff?&order=-createdAt&include=news,user", new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) { }
            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) {
                try {
                    assert response.body() != null;
                    JSONArray ja = new JSONObject(response.body().string()).getJSONArray("results");
                    for (int i = 0; i < ja.length(); i++) {
                        JSONObject jo = ja.getJSONObject(i);
                        JSONObject jo_news = jo.getJSONObject("news");
                        JSONObject jo_user = jo.getJSONObject("user");
                        User news_user= new User(jo_user.getString("email"), "", jo_user.getString("objectId"), jo_user.getString("username"), jo_user.getString("nickname"), jo_user.getBoolean("isAdmin"));
                       if (jo.getString("process").equals("待受理")){
                           if (jo_news.isNull("objectId")){
                               data.add(new TipOffBean(jo.getString("objectId"),jo_user.getString("objectId"),"",jo.getString("content"),jo.getString("createdAt"),jo_user.getString("nickname"),new NewsBean("","该新闻已被删除","无内容：该新闻已被删除","","已删除",null,news_user),jo.getString("process")));
                           }else{
                               data.add(new TipOffBean(jo.getString("objectId"),jo_user.getString("objectId"),jo_news.getString("objectId"),jo.getString("content"),jo.getString("createdAt"),jo_user.getString("nickname"),new NewsBean(jo_news.getString("objectId"),jo_news.getString("title"),jo_news.getString("content"),jo_news.getString("ownerId"),jo_news.getString("createdAt"),null,news_user),jo.getString("process")));
                           }
                       }
                    }
                    adminActivity.runOnUiThread(() -> binding.getAdp().notifyDataSetChanged());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
